package com.xiao.xin.core.Interceptor;

import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;
import java.util.List;

/***
 * 配置服务端拦截器，用于拦截接受数据
 */
@Slf4j
public class WebscoketUserInterceptor implements ChannelInterceptor {

    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (accessor!=null&&StompCommand.CONNECT.equals(accessor.getCommand())) {
            List<String> clientIds = accessor.getNativeHeader("clientId");
            if(clientIds!=null&&clientIds.size()>0) {
                String clientId = clientIds.get(0);
                log.info("设置用户 Principal: {}", clientId);
                accessor.setUser(new Principal() {
                    @Override
                    public String getName() {
                        return clientId;
                    }
                });
            }else {
                log.error("连接时未传 clientId");
            }
        }
        return message;
    }

}
